package com.example.casper.jnuexperiment2025.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.casper.jnuexperiment2025.activity.BookDetailsActivity;
import com.example.casper.jnuexperiment2025.data.Book;
import com.example.casper.jnuexperiment2025.R;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class BookListFragment extends Fragment {

    private shopItemsAdapter adapter;
    private List<Book> books;
    private int currentPosition = -1; // 记录长按位置

    private ActivityResultLauncher<Intent> editLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == AppCompatActivity.RESULT_OK && result.getData() != null) {
                        Intent data = result.getData();
                        String bookName = data.getStringExtra("bookName");
                        double price = data.getDoubleExtra("price", 0.0);
                        boolean isEdit = data.getBooleanExtra("isEdit", false);

                        if (isEdit) {
                            // 更新操作
                            if (currentPosition >= 0 && currentPosition < books.size()) {
                                Book book = books.get(currentPosition);
                                book.setTitle(bookName);
                                book.setPrice(price);
                                // 局部刷新
                                adapter.notifyItemChanged(currentPosition);
                                Toast.makeText(getContext(), "更新成功", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            // 添加操作
                            Book newBook = new Book(bookName, R.drawable.book_no_name, price); // 保存价格
                            int insertPosition = currentPosition + 1;
                            if (insertPosition > books.size()) {
                                insertPosition = books.size();
                            }
                            books.add(insertPosition, newBook);
                            // 局部刷新
                            adapter.notifyItemInserted(insertPosition);
                            Toast.makeText(getContext(),
                                    "添加成功，价格: ¥" + price, Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局
        View rootView = inflater.inflate(R.layout.fragment_book_list, container, false);
        
        // 从文件读取数据
        books = loadBooksData();
        RecyclerView recyclerView = rootView.findViewById(R.id.recycler_view_my_books);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new shopItemsAdapter(books);
        recyclerView.setAdapter(adapter);

        registerForContextMenu(recyclerView);
        
        return rootView;
    }

    private List<Book> getListBooks() {
        List<Book> books = new ArrayList<>();
        books.add(new Book("无名之书", R.drawable.book_no_name, 29.9));
        books.add(new Book("软件项目管理案例教程（第3版）", R.drawable.book_2, 45.0));
        books.add(new Book("信息安全数学基础（第2版）", R.drawable.book_1, 38.5));
        return books;
    }

    // 保存数据到文件
    private void saveBooksData() {
        if (getContext() == null) return;
        
        Log.d("BookListFragment", "开始保存数据，共有" + books.size() + "本书籍");
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = getContext().openFileOutput("books_data.dat", AppCompatActivity.MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(books);
            oos.flush();
            Log.d("BookListFragment", "数据保存成功");
        } catch (IOException e) {
            Log.e("BookListFragment", "保存数据失败", e);
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) oos.close();
                if (fos != null) fos.close();
            } catch (IOException e) {
                Log.e("BookListFragment", "关闭流失败", e);
                e.printStackTrace();
            }
        }
    }

    // 从文件读取数据
    private List<Book> loadBooksData() {
        if (getContext() == null) return getListBooks();

        Log.d("BookListFragment", "开始读取数据");
        List<Book> loadedBooks = null;

        // 使用 try-with-resources 自动管理资源
        try (FileInputStream fis = getContext().openFileInput("books_data.dat");
             ObjectInputStream ois = new ObjectInputStream(fis)) {

            loadedBooks = (List<Book>) ois.readObject();
            Log.d("BookListFragment", "读取数据成功，共有" + loadedBooks.size() + "本书籍");

        } catch (IOException | ClassNotFoundException e) {
            Log.e("BookListFragment", "读取数据失败，使用默认数据", e);
            // 如果文件不存在或读取失败，返回默认数据
            loadedBooks = getListBooks();
            Log.d("BookListFragment", "使用默认数据，共有" + loadedBooks.size() + "本书籍");
        }
        return loadedBooks;
    }

    // 创建上下文菜单
    @Override
    public void onCreateContextMenu(@NonNull ContextMenu menu, @NonNull View v, @Nullable ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (getContext() != null) {
            getActivity().getMenuInflater().inflate(R.menu.recycler_context_menu, menu);
        }
    }

    // 处理菜单项点击
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        if (currentPosition == -1) return false;

        int itemId = item.getItemId();
        if (itemId == R.id.menu_add) {
            // 添加
            Intent addIntent = new Intent(getContext(), BookDetailsActivity.class);
            addIntent.putExtra("isEdit", false);
            editLauncher.launch(addIntent);
            return true;
        } else if (itemId == R.id.menu_edit) {
            // 编辑
            Intent editIntent = new Intent(getContext(), BookDetailsActivity.class);
            editIntent.putExtra("isEdit", true);
            editIntent.putExtra("bookName", books.get(currentPosition).getTitle());
            editIntent.putExtra("price", books.get(currentPosition).getPrice());
            editLauncher.launch(editIntent);
            return true;
        } else if (itemId == R.id.menu_delete) {
            // 删除对话框
            new AlertDialog.Builder(getContext())
                    .setTitle("确认删除")
                    .setMessage("确定要删除《" + books.get(currentPosition).getTitle() + "》吗？")
                    .setPositiveButton("删除", (dialog, which) -> {
                        String deletedBookName = books.get(currentPosition).getTitle();
                        books.remove(currentPosition);
                        // 局部刷新
                        adapter.notifyItemRemoved(currentPosition);
                        Toast.makeText(getContext(),
                                "《" + deletedBookName + "》已删除", Toast.LENGTH_SHORT).show();
                    })
                    .setNegativeButton("取消", null)
                    .show();
            return true;
        } else {
            return super.onContextItemSelected(item);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在Fragment暂停时保存数据
        saveBooksData();
    }

    public class shopItemsAdapter extends RecyclerView.Adapter<shopItemsAdapter.ViewHolder> {

        private List<Book> localDataSet;

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            private final android.widget.ImageView bookCover;
            private final android.widget.TextView bookName;

            public ViewHolder(View view) {
                super(view);
                bookCover = view.findViewById(R.id.image_view_book_cover);
                bookName = view.findViewById(R.id.text_view_book_name);

                // 设置长按监听
                view.setOnCreateContextMenuListener(this);
                view.setOnLongClickListener(v -> {
                    currentPosition = getAbsoluteAdapterPosition();
                    return false;
                });
            }

            public android.widget.TextView getBookName() {
                return bookName;
            }

            public android.widget.ImageView getBookCover() {
                return bookCover;
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                // 上下文菜单已在Fragment中创建，无需额外操作
            }
        }

        public shopItemsAdapter(List<Book> dataSet) {
            localDataSet = dataSet;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_book, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, final int position) {
            Book book = localDataSet.get(position);
            viewHolder.getBookName().setText(book.getTitle());
            viewHolder.getBookCover().setImageResource(book.getCoverResourceId());
        }

        @Override
        public int getItemCount() {
            return localDataSet.size();
        }
    }
}